#include "McpComplex.h"
#include "settings.h"
#include "mcp_server.h"
#include <esp_log.h>
#include "board.h"
#include "display.h"
#include <string>
#include <stdio.h>
#define TAG "McpComplex"

bool McpComplex::RefreshFollowerCount()
{
    if (uid_.empty())
    {
        ESP_LOGE(TAG, "UID is not set");
        return false;
    }

    if (refresh_in_progress_)
    {
        ESP_LOGI(TAG, "Refresh already in progress");
        return false;
    }

    refresh_in_progress_ = true;

    // auto &board = Board::GetInstance();
    // auto http = board.CreateHttp();

    // auto http = Board::GetInstance()->CreateHttp(0);
    auto &board = Board::GetInstance();
    auto network = board.GetNetwork();
    auto http = network->CreateHttp(0);

    std::string url = "https://api.bilibili.com/x/relation/stat?vmid=" + uid_;
    http->SetHeader("User-Agent", "Mozilla/5.0");

    if (!http->Open("GET", url))
    {
        ESP_LOGE(TAG, "Failed to open HTTP connection");
        http->Close();
        refresh_in_progress_ = false;
        return false;
    }

    std::string response = http->ReadAll();
    http->Close();
    // Add response debugging
    ESP_LOGD(TAG, "Raw API response: %.*s...", 200, response.c_str());
    cJSON *root = cJSON_Parse(response.c_str());
    if (root == NULL)
    {
        // ESP_LOGE(TAG, "Failed to parse JSON response");
        const char *error_ptr = cJSON_GetErrorPtr();
        if (error_ptr != NULL)
        {
            ESP_LOGE(TAG, "JSON parse error before: %s", error_ptr);
        }
        refresh_in_progress_ = false;
        return false;
    }

    cJSON *code = cJSON_GetObjectItem(root, "code");
    if (code == NULL || code->valueint != 0)
    {
        ESP_LOGE(TAG, "API returned error code");
        cJSON_Delete(root);
        refresh_in_progress_ = false;
        return false;
    }

    cJSON *data = cJSON_GetObjectItem(root, "data");
    if (data == NULL)
    {
        ESP_LOGE(TAG, "No data field in response");
        cJSON_Delete(root);
        refresh_in_progress_ = false;
        return false;
    }

    cJSON *follower = cJSON_GetObjectItem(data, "follower");
    if (follower == NULL)
    {
        ESP_LOGE(TAG, "No follower field in data");
        cJSON_Delete(root);
        refresh_in_progress_ = false;
        return false;
    }

    follower_count_ = follower->valueint;
    ESP_LOGI(TAG, "B站用户 %s 的粉丝数：%d", uid_.c_str(), follower_count_);

    cJSON_Delete(root);
    refresh_in_progress_ = false;
    return true;
}

bool McpComplex::get_hitokoto()
{

    refresh_in_progress_ = true;
    auto &board = Board::GetInstance();

    auto network = board.GetNetwork();
    auto http = network->CreateHttp(0);

    std::string url = "https://v1.hitokoto.cn/";
    http->SetHeader("User-Agent", "Mozilla/5.0");

    if (!http->Open("GET", url))
    {
        ESP_LOGE(TAG, "Failed to open HTTP connection");
        http->Close();
        refresh_in_progress_ = false;
        return false;
    }

    std::string response = http->ReadAll();
    http->Close();

    cJSON *root = cJSON_Parse(response.c_str());
    if (root == NULL)
    {
        ESP_LOGE(TAG, "Failed to parse JSON response");
        refresh_in_progress_ = false;
        return false;
    }

    cJSON *hitokoto = cJSON_GetObjectItem(root, "hitokoto");
    if (hitokoto && cJSON_IsString(hitokoto))
    {
        hitokoto_ = hitokoto->valuestring;
        from_ = cJSON_GetObjectItem(root, "from")->valuestring;
        ESP_LOGI(TAG, "成功提取一言内容: %s", hitokoto_.c_str());
        ESP_LOGI(TAG, "出自: %s", from_.c_str());
    }

    cJSON_Delete(root);
    refresh_in_progress_ = false;
    return true;
}

bool McpComplex::get_note()
{
    refresh_in_progress_ = true;
    auto &board = Board::GetInstance();
    auto network = board.GetNetwork();
    auto http = network->CreateHttp(0);
    std::string url = "https://open.iciba.com/dsapi/";

    // 添加 HTTPS 配置
    // http->SetSSLVerify(false);  // 禁用 SSL 证书验证
    http->SetHeader("User-Agent", "Mozilla/5.0 (ESP32)");
    http->SetTimeout(10000); // 设置 10 秒超时

    // if (!http->Open("GET", url)) {
    //     ESP_LOGE(TAG, "打开 HTTP 连接失败");
    //     http->Close();
    //     refresh_in_progress_ = false;
    //     return false;
    // }
    for (int retry = 0; retry < 3; retry++)
    {
        if (http->Open("GET", url))
            break;
        vTaskDelay(1000 / portTICK_PERIOD_MS);
    }
    // 读取并检查响应
    std::string response = http->ReadAll();
    http->Close();

    if (response.empty())
    {
        ESP_LOGE(TAG, "收到空响应");
        refresh_in_progress_ = false;
        return false;
    }

    // 解析 JSON
    cJSON *root = cJSON_Parse(response.c_str());
    if (!root)
    {
        ESP_LOGE(TAG, "JSON 解析失败");
        refresh_in_progress_ = false;
        return false;
    }

    // 安全获取字段
    cJSON *content = cJSON_GetObjectItem(root, "content");
    cJSON *note = cJSON_GetObjectItem(root, "note");

    if (content && note && cJSON_IsString(content) && cJSON_IsString(note))
    {
        everyday_soup_ = std::string(content->valuestring) + "\n" + note->valuestring;
        ESP_LOGI(TAG, "成功获取鸡汤文: %s", everyday_soup_.c_str());
    }
    else
    {
        ESP_LOGE(TAG, "无效的 JSON 字段");
        cJSON_Delete(root);
        refresh_in_progress_ = false;
        return false;
    }

    cJSON_Delete(root);
    refresh_in_progress_ = false;
    return true;
}

void McpComplex::wifi_event_handler(void *arg, esp_event_base_t event_base, int32_t event_id, void *event_data)
{
    McpComplex *instance = static_cast<McpComplex *>(arg);

    if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP)
    {
        ESP_LOGI("BiliFans", "Wi-Fi connected, updating fans count...");
        instance->OnWifiConnected();
    }
    if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED)
    {
        ESP_LOGW("BiliFans", "Wi-Fi disconnected, pausing update timer...");
        instance->OnWifiDisconnected();
    }
}

void McpComplex::OnWifiConnected()
{
    wifi_connected_ = true;
    UpdateFansCount();
    if (clock_timer_handle_)
    {
        esp_timer_start_periodic(clock_timer_handle_, 5 * 60 * 1000000);
    }
}

void McpComplex::OnWifiDisconnected()
{
    wifi_connected_ = false;
    if (clock_timer_handle_)
    {
        esp_timer_stop(clock_timer_handle_);
    }
}

void McpComplex::UpdateFansCount()
{
    RefreshFollowerCount();
    if (follower_count_ < 0)
    {
        ESP_LOGE(TAG, "Failed to get fans count");
    }
    ESP_LOGI(TAG, "Fans count updated: %d", follower_count_);
}
void McpComplex::InitializeEvent()
{
    esp_timer_create_args_t clock_timer_args = {
        .callback = [](void *arg)
        {
            McpComplex *instance = (McpComplex *)(arg);
            instance->UpdateFansCount();
        },
        .arg = this,
        .dispatch_method = ESP_TIMER_TASK,
        .name = "BiliFansUpdateTimer",
        .skip_unhandled_events = true};
    esp_timer_create(&clock_timer_args, &clock_timer_handle_);

    ESP_ERROR_CHECK(esp_event_handler_register(IP_EVENT, IP_EVENT_STA_GOT_IP, &McpComplex::wifi_event_handler, this));
    ESP_ERROR_CHECK(esp_event_handler_register(WIFI_EVENT, WIFI_EVENT_STA_DISCONNECTED, &McpComplex::wifi_event_handler, this));
}

void McpComplex::InitializeGpioPins()
{
    // 初始化P0和P1引脚为输出模式
    gpio_config_t io_conf = {};
    io_conf.intr_type = GPIO_INTR_DISABLE;
    io_conf.mode = GPIO_MODE_OUTPUT;
    io_conf.pin_bit_mask = (1ULL << MCP_P0_GPIO) | (1ULL << MCP_P1_GPIO);
    io_conf.pull_down_en = GPIO_PULLDOWN_DISABLE;
    io_conf.pull_up_en = GPIO_PULLUP_DISABLE;
    gpio_config(&io_conf);
    
    // 初始化引脚状态为低电平
    gpio_set_level(MCP_P0_GPIO, 0);
    gpio_set_level(MCP_P1_GPIO, 0);
    p0_state_ = false;
    p1_state_ = false;
    
    ESP_LOGI(TAG, "P0和P1接口初始化完成");
}

bool McpComplex::SetP0Output(bool state)
{
    gpio_set_level(MCP_P0_GPIO, state ? 1 : 0);
    p0_state_ = state;
    ESP_LOGI(TAG, "P0接口(雾化器)设置为: %s", state ? "高电平" : "低电平");
    return true;
}

bool McpComplex::SetP1Output(bool state)
{
    gpio_set_level(MCP_P1_GPIO, state ? 1 : 0);
    p1_state_ = state;
    ESP_LOGI(TAG, "P1接口(LED灯带)设置为: %s", state ? "高电平" : "低电平");
    return true;
}

bool McpComplex::GetP0State()
{
    return p0_state_;
}

bool McpComplex::GetP1State()
{
    return p1_state_;
}

// 解析 "温度:xx.x°C湿度:yy.y%" 字符串
bool McpComplex::ParseTempHumid(const std::string& s, float& temp, float& humid)
{
    const std::string tpfx = "温度:";
    const std::string tsp  = "°C";
    const std::string hpfx = "湿度:";
    const std::string hsp  = "%";
    size_t t1 = s.find(tpfx);
    size_t t2 = (t1 != std::string::npos) ? s.find(tsp, t1) : std::string::npos;
    if (t1 == std::string::npos || t2 == std::string::npos) return false;
    std::string tsub = s.substr(t1 + tpfx.size(), t2 - (t1 + tpfx.size()));
    try { temp = std::stof(tsub); } catch (...) { return false; }

    size_t h1 = s.find(hpfx, t2);
    size_t h2 = (h1 != std::string::npos) ? s.find(hsp, h1) : std::string::npos;
    if (h1 == std::string::npos || h2 == std::string::npos) return false;
    std::string hsub = s.substr(h1 + hpfx.size(), h2 - (h1 + hpfx.size()));
    try { humid = std::stof(hsub); } catch (...) { return false; }

    return true;
}

void McpComplex::EnvControlTick()
{
    auto &board = Board::GetInstance();
    std::string s = board.get_temp_humid_sensor();
    float t = 0.0f, h = 0.0f;
    if (!ParseTempHumid(s, t, h)) {
        ESP_LOGW(TAG, "Failed to parse temp/humid: %s", s.c_str());
        return;
    }

    // 温度控制：低于阈值 -> 开启P1(LED加热)，否则关闭
    if (temp_ctrl_enabled_) {
        bool want_p1 = (t < temp_min_threshold_);
        if (want_p1 != p1_state_) {
            SetP1Output(want_p1);
            auto *disp = board.GetDisplay();
            if (disp) {
                char msg[96];
                snprintf(msg, sizeof(msg),
                         want_p1 ? "温度%.1f°C低于阈值%.1f°C，开启LED加热" : "温度%.1f°C达到阈值%.1f°C，关闭LED加热",
                         t, temp_min_threshold_);
                disp->ShowNotification(msg, 3000);
            }
        }
    }

    // 湿度控制：低于阈值 -> 开启P0(雾化加湿)，否则关闭
    if (humid_ctrl_enabled_) {
        bool want_p0 = (h < humid_min_threshold_);
        if (want_p0 != p0_state_) {
            SetP0Output(want_p0);
            auto *disp = board.GetDisplay();
            if (disp) {
                char msg[96];
                snprintf(msg, sizeof(msg),
                         want_p0 ? "湿度%.1f%%低于阈值%.1f%%，开启雾化器" : "湿度%.1f%%达到阈值%.1f%%，关闭雾化器",
                         h, humid_min_threshold_);
                disp->ShowNotification(msg, 3000);
            }
        }
    }
}

void McpComplex::StartEnvControlTimer()
{
    if (env_ctrl_timer_handle_) {
        esp_timer_start_periodic(env_ctrl_timer_handle_, 3 * 1000 * 1000); // 3s
    }
}

void McpComplex::StopEnvControlTimer()
{
    if (env_ctrl_timer_handle_) {
        esp_timer_stop(env_ctrl_timer_handle_);
    }
}

McpComplex::McpComplex()
{
    // 从设置中读取亮度等级
    // InitializeEvent();
    
    // 初始化GPIO引脚
    InitializeGpioPins();

    auto &mcp_server = McpServer::GetInstance();

    // 读取阈值配置与开关（默认温度25℃、湿度50%，均启用）
    {
        Settings s("env_control");
        temp_min_threshold_ = static_cast<float>(s.GetInt("temp_min", 25));
        humid_min_threshold_ = static_cast<float>(s.GetInt("humid_min", 50));
        temp_ctrl_enabled_ = (s.GetInt("temp_enabled", 1) != 0);
        humid_ctrl_enabled_ = (s.GetInt("humid_enabled", 1) != 0);
    }

    // MCP: 获取设置
    mcp_server.AddTool("self.env_control.get_settings",
                       "获取温/湿度阈值与自动控制开关",
                       PropertyList(), [this](const PropertyList&) -> ReturnValue {
                           std::string json =
                               std::string("{\"temp_min\":") + std::to_string(temp_min_threshold_) +
                               ",\"humid_min\":" + std::to_string(humid_min_threshold_) +
                               ",\"temp_enabled\":" + (temp_ctrl_enabled_ ? "true" : "false") +
                               ",\"humid_enabled\":" + (humid_ctrl_enabled_ ? "true" : "false") +
                               ",\"p0_state\":" + (GetP0State() ? "true" : "false") +
                               ",\"p1_state\":" + (GetP1State() ? "true" : "false") + "}";
                           return json;
                       });

    // MCP: 设置温度最低阈值(整数℃)
    mcp_server.AddTool("self.env_control.set_temp_threshold",
                       "设置温度最低阈值(整数℃)，低于该值开启LED灯带加热",
                       PropertyList({ Property("min", kPropertyTypeInteger, -20, 80) }),
                       [this](const PropertyList &properties) -> ReturnValue {
                           int v = properties["min"].value<int>();
                           temp_min_threshold_ = static_cast<float>(v);
                           Settings sw("env_control", true);
                           sw.SetInt("temp_min", v);
                           return true;
                       });

    // MCP: 设置湿度最低阈值(整数%)
    mcp_server.AddTool("self.env_control.set_humid_threshold",
                       "设置湿度最低阈值(整数%)，低于该值开启雾化器加湿",
                       PropertyList({ Property("min", kPropertyTypeInteger, 0, 100) }),
                       [this](const PropertyList &properties) -> ReturnValue {
                           int v = properties["min"].value<int>();
                           humid_min_threshold_ = static_cast<float>(v);
                           Settings sw("env_control", true);
                           sw.SetInt("humid_min", v);
                           return true;
                       });

    // MCP: 启用/禁用温度自动控制
    mcp_server.AddTool("self.env_control.enable_temp_control",
                       "启用或禁用温度自动控制",
                       PropertyList({ Property("enabled", kPropertyTypeBoolean) }),
                       [this](const PropertyList &properties) -> ReturnValue {
                           bool en = properties["enabled"].value<bool>();
                           temp_ctrl_enabled_ = en;
                           Settings sw("env_control", true);
                           sw.SetInt("temp_enabled", en ? 1 : 0);
                           return true;
                       });

    // MCP: 启用/禁用湿度自动控制
    mcp_server.AddTool("self.env_control.enable_humid_control",
                       "启用或禁用湿度自动控制",
                       PropertyList({ Property("enabled", kPropertyTypeBoolean) }),
                       [this](const PropertyList &properties) -> ReturnValue {
                           bool en = properties["enabled"].value<bool>();
                           humid_ctrl_enabled_ = en;
                           Settings sw("env_control", true);
                           sw.SetInt("humid_enabled", en ? 1 : 0);
                           return true;
                       });

    // MCP: 立即执行一次阈值判断
    mcp_server.AddTool("self.env_control.apply_now",
                       "立即读取温湿度并执行一次阈值控制判断",
                       PropertyList(), [this](const PropertyList&) -> ReturnValue {
                           EnvControlTick();
                           return true;
                       });

    // 创建并启动3秒周期的环境控制定时器
    {
        esp_timer_create_args_t env_args = {
            .callback = [](void *arg) {
                static_cast<McpComplex*>(arg)->EnvControlTick();
            },
            .arg = this,
            .dispatch_method = ESP_TIMER_TASK,
            .name = "EnvCtrlTimer",
            .skip_unhandled_events = true
        };
        ESP_ERROR_CHECK(esp_timer_create(&env_args, &env_ctrl_timer_handle_));
        ESP_ERROR_CHECK(esp_timer_start_periodic(env_ctrl_timer_handle_, 3 * 1000 * 1000));
    }

    mcp_server.AddTool("self.get_temp_humid",
                       "获取板载温湿度传感器数据",
                       PropertyList(), [this](const PropertyList &properties) -> ReturnValue
                       {
                        auto &board = Board::GetInstance();
                        std::string temp_humid = board.get_temp_humid_sensor();
                        // board.GetDisplay()->ShowNotification(temp_humid,3000);
                        board.GetDisplay()->ShowMessageButton(temp_humid,6000);
                        return temp_humid; });

    mcp_server.AddTool("self.get_als_sensor",
                       "获取板载光照强度传感器数据",
                       PropertyList(), [this](const PropertyList &properties) -> ReturnValue
                       {
                        auto &board = Board::GetInstance();
                        std::string als_data = board.get_als_sensor();
                        // board.GetDisplay()->ShowNotification(als_data,3000);
                        board.GetDisplay()->ShowMessageButton(als_data,6000);
                        return als_data; });

    // 获取board和display的引用


    mcp_server.AddTool("self.BilibiliFans.uid",
                       "B站用户ID",
                       PropertyList(), [this](const PropertyList &properties) -> ReturnValue
                       { return uid_; });
    mcp_server.AddTool("self.BilibiliFans.set_uid",
                       "设置B站用户ID",
                       PropertyList({Property("uid", kPropertyTypeString)}), [this](const PropertyList &properties) -> ReturnValue
                       {
            uid_ = properties["uid"].value<std::string>();
            ESP_LOGI(TAG, "设置B站用户ID为: %s", uid_.c_str());
            return true; });
    mcp_server.AddTool("self.BilibiliFans.report_fansCount",
                       "汇报粉丝数量",
                       PropertyList(), [this](const PropertyList &properties) -> ReturnValue
                       { 
                        UpdateFansCount();
                        return follower_count_; });

    mcp_server.AddTool("self.BilibiliFans.flash_fansCount",
                       "刷新粉丝数量",
                       PropertyList(), [this](const PropertyList &properties) -> ReturnValue
                       {
        ESP_LOGI(TAG, "刷新B站粉丝数量");
        UpdateFansCount();
        return true; });
    mcp_server.AddTool("self.tts",
                       "复读机功能当用户说TTS_{文本}例如TTS_{你好}那么提取文本你好返回给用户，不说其他废话，只说需要复读的内容\n"
                       "参数:\n"
                       "  `text`: 用户播放文本\n"
                       "功能:\n"
                       "  原样不修改重复用户说的话\n"
                       "返回:\n"
                       "  成功或失败的状态及提示信息",
                       PropertyList({Property("text", kPropertyTypeString)}),
                       [this](const PropertyList &properties) -> ReturnValue
                       {
                           // 1. 参数验证
                           std::string text = properties["text"].value<std::string>();
                           return "{\"success\": true, \"message\": \"" + std::string(text) + "\"}";
                       });
    mcp_server.AddTool("self.translator",
                       "同声传译功能当用户说翻译_{文本}例如翻译_{你好}那么提取文本并翻译成英语返回给用户，如果用户说的是英文就把所说内容翻译成中文，不说其他废话 \n"
                       "参数:\n"
                       "  `text`: 中英互译用户所说的文本\n"
                       "功能:\n"
                       "   中英互译用户所说的文本\n"
                       "返回:\n"
                       "  成功或失败的状态及提示信息",
                       PropertyList({Property("text", kPropertyTypeString)}),
                       [this](const PropertyList &properties) -> ReturnValue
                       {
                           // 1. 参数验证
                           std::string text = properties["text"].value<std::string>();
                           return "{\"success\": true, \"message\": \"" + std::string(text) + "\"}";
                       });

    mcp_server.AddTool("self.get_hitokoto",
                       "给我开心地随便说一句话，一言",
                       PropertyList(), [this](const PropertyList &properties) -> ReturnValue
                       {
                        get_hitokoto();
                           return hitokoto_; });
    mcp_server.AddTool("self.hitokoto_source",
                       "刚才随便说的那一句是出自哪里",
                       PropertyList(), [this](const PropertyList &properties) -> ReturnValue
                       { return from_; });
    mcp_server.AddTool("self.get_note",
                       "获取每日中英对照鸡汤文",
                       PropertyList(), [this](const PropertyList &properties) -> ReturnValue
                       {
         get_note();
                           return  everyday_soup_; });

    // 添加P0接口(雾化器)控制工具
    mcp_server.AddTool("self.control_p0",
                       "控制P0接口(雾化器)的开关状态。P0接口连接GPIO1，用于控制雾化器设备。",
                       PropertyList({Property("state", kPropertyTypeBoolean)}),
                       [this](const PropertyList &properties) -> ReturnValue
                       {
                           bool state = properties["state"].value<bool>();
                           if (SetP0Output(state)) {
                               auto &board = Board::GetInstance();
                               std::string message = state ? "雾化器已启动" : "雾化器已关闭";
                               board.GetDisplay()->ShowNotification(message, 3000);
                               return "{\"success\": true, \"message\": \"" + message + "\", \"p0_state\": " + (state ? "true" : "false") + "}";
                           }
                           return "{\"success\": false, \"message\": \"P0接口控制失败\"}";
                       });

    // 添加P1接口(LED灯带)控制工具
    mcp_server.AddTool("self.control_p1",
                       "控制P1接口(LED灯带)的开关状态。P1接口连接GPIO2，用于控制LED灯带设备。",
                       PropertyList({Property("state", kPropertyTypeBoolean)}),
                       [this](const PropertyList &properties) -> ReturnValue
                       {
                           bool state = properties["state"].value<bool>();
                           if (SetP1Output(state)) {
                               auto &board = Board::GetInstance();
                               std::string message = state ? "LED灯带已启动" : "LED灯带已关闭";
                               board.GetDisplay()->ShowNotification(message, 3000);
                               return "{\"success\": true, \"message\": \"" + message + "\", \"p1_state\": " + (state ? "true" : "false") + "}";
                           }
                           return "{\"success\": false, \"message\": \"P1接口控制失败\"}";
                       });

    // 添加获取P0和P1状态的工具
    mcp_server.AddTool("self.get_gpio_status",
                       "获取P0和P1接口的当前状态。P0控制雾化器(GPIO1)，P1控制LED灯带(GPIO2)。",
                       PropertyList(),
                       [this](const PropertyList &properties) -> ReturnValue
                       {
                           auto &board = Board::GetInstance();
                           std::string status = "P0(雾化器):" + std::string(GetP0State() ? "开启" : "关闭") + 
                                              ", P1(LED灯带):" + std::string(GetP1State() ? "开启" : "关闭");
                           board.GetDisplay()->ShowMessageButton(status, 5000);
                           return "{\"p0_state\": " + std::string(GetP0State() ? "true" : "false") + 
                                  ", \"p1_state\": " + std::string(GetP1State() ? "true" : "false") + 
                                  ", \"message\": \"" + status + "\"}";
                       });

    // 添加同时控制P0和P1的工具
    mcp_server.AddTool("self.control_both_gpio",
                       "同时控制P0和P1接口的开关状态。可以同时控制雾化器和LED灯带。",
                       PropertyList({
                           Property("p0_state", kPropertyTypeBoolean),
                           Property("p1_state", kPropertyTypeBoolean)
                       }),
                       [this](const PropertyList &properties) -> ReturnValue
                       {
                           bool p0_state = properties["p0_state"].value<bool>();
                           bool p1_state = properties["p1_state"].value<bool>();
                           
                           bool p0_success = SetP0Output(p0_state);
                           bool p1_success = SetP1Output(p1_state);
                           
                           if (p0_success && p1_success) {
                               auto &board = Board::GetInstance();
                               std::string message = "雾化器:" + std::string(p0_state ? "开启" : "关闭") + 
                                                   ", LED灯带:" + std::string(p1_state ? "开启" : "关闭");
                               board.GetDisplay()->ShowNotification(message, 3000);
                               return "{\"success\": true, \"message\": \"" + message + "\", \"p0_state\": " + 
                                      (p0_state ? "true" : "false") + ", \"p1_state\": " + (p1_state ? "true" : "false") + "}";
                           }
                           return "{\"success\": false, \"message\": \"GPIO接口控制失败\"}";
                       });
}
